package com.common.ui.controls;

import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class CountProcess extends DefaultModalProcess 
{

	public CountProcess(String processName, Frame owner) 
	{
		super(processName, owner);
	}

	public boolean canCancel()
	{
		return !(JOptionPane.showConfirmDialog(getOwner(), "Are you sure you want to cancel?","Sure",
				JOptionPane.YES_NO_OPTION)==JOptionPane.YES_NO_CANCEL_OPTION);
	}
	
	@Override
	public void doWork(Object argument) throws Exception 
	{
		int count = ((Integer) argument).intValue();
		for(int i = 1;i<=count && !isCancelled();i++)
		{
			updateInfo("Counting " + i + " of " + count);
			updateStatus("Counting ... " + i, true);
			Thread.sleep(100);
		}
	}

	public void done(Exception ex)
	{
		System.out.println(isCancelled() ? "Aborted ..." : "Done ...");
	}
	
	public static void main(String[] args)
	{
		final JFrame frame = new JFrame("Test");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JPanel panel = new JPanel();
		frame.setContentPane(panel);
		JButton button = new JButton("Start");
		panel.add(button);
		button.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e) 
			{
				doWork(frame);
			}
		});
		SwingUtilities.invokeLater(new Runnable() {
			public void run()
			{
				frame.setSize(800, 600);
				frame.setVisible(true);
			}
		});
	}
	
	public static void doWork(Frame frame)
	{
		CountProcess process  = new CountProcess("Counting. Please wait ...",frame);
		process.start(new Integer(100));
	}
	
}
